package com.yzf.zyfverifycode.utils;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import org.xutils.BuildConfig;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.logging.LogManager;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class HttpXUtils {
    public static int DEFAULT_CACHE_EXPIRY_TIME = 30 * 1000;
    public static void xUtilsPostRequest(Context context,RequestParams params, final MyCallback callback) {
        if (params == null) {
            params = new RequestParams();
        }

        params.setCacheMaxAge(1000 * 0); //为请求添加缓存时间
        params.setConnectTimeout(DEFAULT_CACHE_EXPIRY_TIME);
        final String url = params.getUri();
        SSLContext sslContext = getSSLContext(context);
        if (null == sslContext) {
            return;
        }

        params.setSslSocketFactory(sslContext.getSocketFactory());
        x.http().post(params, new Callback.CacheCallback<String>() {
            private String result = null;

            @Override
            public void onSuccess(String result) {
                Log.i("成功提示。。。。00。。", String.valueOf(result));
                if (result != null) {
                    this.result = result;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("错误提示。。。11。。", String.valueOf(ex.getMessage()));
                Toast.makeText(x.app(), "网络异常", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinished() {
                callback.myResult(result);
            }

            @Override
            public boolean onCache(String result) {
                this.result = result;
                return false;
            }
        });
    }
    private static SSLContext mSSLContext = null;

    /**
     * 获取Https的证书
     *
     * @param context 上下文
     * @return SSL的上下文对象
     */
    private static SSLContext getSSLContext(Context context) {
//        CertificateFactory certificateFactory = null;
//        InputStream inputStream = null;
//        Certificate cer = null;
//        KeyStore keystore = null;
//        TrustManagerFactory trustManagerFactory = null;
        try {
//            certificateFactory = CertificateFactory.getInstance("X.509");
//            inputStream = context.getAssets().open("baidu.cer");//这里导入SSL证书文件
//            try {
//                cer = certificateFactory.generateCertificate(inputStream);
//                Log.i("getSSLContext", cer.getPublicKey().toString());
//            } finally {
//                inputStream.close();
//            }

//            //创建一个证书库，并将证书导入证书库
//            keystore = KeyStore.getInstance(KeyStore.getDefaultType());
//            keystore.load(null, null); //双向验证时使用
//            keystore.setCertificateEntry("trust", cer);
//
//            // 实例化信任库
//            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//            trustManagerFactory.init(keystore);

            mSSLContext = SSLContext.getInstance("TLS");
//            mSSLContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());

            //信任所有证书 （官方不推荐使用）
            mSSLContext.init(null, new TrustManager[]{new X509TrustManager() {

              @Override
              public X509Certificate[] getAcceptedIssuers() {
                  return null;
              }

              @Override
              public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                      throws CertificateException {

              }

              @Override
              public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                      throws CertificateException {

              }
          }}, new SecureRandom());

            return mSSLContext;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public interface MyCallback {
        void myResult(String result);
    }
}
